import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { addTodo } from '../../store/actions/todo'

export default function TotoHeader() {
  const [name, setName] = useState('')
  const dispatch = useDispatch()
  const handleAdd = (e) => {
    if (e.keyCode === 13) {
      if (name.trim().length === 0) return alert('不能为空')
      dispatch(addTodo(name))
      setName('')
    }
  }
  return (
    <header className='header'>
      <h1>todos</h1>
      <input
        className='new-todo'
        placeholder='What needs to be done?'
        autoFocus
        value={name}
        onChange={(e) => setName(e.target.value)}
        onKeyUp={handleAdd}
      />
    </header>
  )
}
